# -*- coding: utf-8 -*-
'''
Created on 2012-8-22

@author: null
'''
from dao import UserDataAccess
from service import BaseService
import models
import hashlib
from flaskext.babel import gettext

class UserService(BaseService):
    def get_user_by_email(self, email):
        if not email:
            raise Exception(gettext(u"email cannot be empty."));
        
        userDataAccess = UserDataAccess();
        result = userDataAccess.get_user(email);
        return result;

    def add_user(self, user):
        """
        Create new User.
        """
        if user == None:
            raise Exception(gettext(u"user cannot be empty."));
        if not isinstance(user, models.User):
            raise Exception(gettext(u"user parameter must be a instance of 'User' type."));
        if not user.email:
            raise Exception(gettext(u"Email cannot be empty"));
        if not user.display_name:
            raise Exception(gettext(u"Display Name cannot be empty."));

        userDataAccess = UserDataAccess(); 
        user.email = user.email.lower();
        if userDataAccess.is_email_registered(user.email):
            raise Exception(gettext(u"Email has already been registered."));
        
        if user.password == "":
            user.password = None;
        else:
            user.password = self._one_way_encrypt(user.password, user.email);
            
        return userDataAccess.add_user(user);
    
    def get_user(self, email):
        userDataAccess = UserDataAccess();
        return userDataAccess.get_user(email);
    
    def _one_way_encrypt(self, text, salt):
        if not text:
            return text;
        else:
            return hashlib.sha256(text + salt).hexdigest();
        
    def check_auth(self, email, password, is_encrypted_password=False): 
        """
        Check whether the specified User is authorized.
        """
        userDataAccess = UserDataAccess();
        User = userDataAccess.get_user(email);
        if User:
            if User.password:
                encrypted_password = password;
                if not is_encrypted_password:
                    encrypted_password = self._one_way_encrypt(password, email);
                return encrypted_password == User.password;
            else:
                if not User.password and not password:
                    return True;
                
        return False;
                
        
    
